from django.utils import simplejson as json
from project.travel_game.models import *
from django.template.loader import Template, Context
from django.contrib.auth import authenticate
from django.contrib.auth import login as djangoLogin, logout as djangoLogout
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.models import User
from project.travel_game.forms import teamInfoForm, paceForm, rationForm, userCreationForm
from project.travel_game.sayingsList import sayingsList

import random
import math
from datetime import timedelta



@login_required
def startUp(request):
    '''
    Function to load initial form to create a new game
    Inputs: request
    Outputs: Rendered HTTP response
    request: A Django HTTPRequest object with all client info
    '''
    # Create empty context dictionary for rendering the template
    context = {}
    context.update(csrf(request))
    # create unbound teamInfoForm and place in context dictionary
    context['teamInfoForm'] = teamInfoForm()
    # render startUpMenu template and return to the user
    return render_to_response('html/startUpMenu.html',context,context_instance=RequestContext(request))

def getQuote(context):
    '''
    Function to get a funny quote
    Outputs: Json with the quote.  The quote is delivered from the mindset of
            of someone living in the time period during which Oregon Trail takes
            place.
    '''
    return HttpResponse(json.dumps({'quote':sayingsList[random.randint(0,len(sayingsList)-1)]}))

def contextVariableDefaultContent(request):
    '''
    Function that when added to TEMPLATE_CONTEXT_PROCESSORS will be put 
    variables into every context by default
    Inputs: request
    Outputs: context
    
    'message' is a variable that causes a message to be displayed on whatever
    page is loaded next by creating a hidden div that the javascript looks for
    and displays a jquery dialog box if found
    
    'currentGame' contains the logged in user's current game object, allowing
    views to access all of the info for that game through that object and its
    relationships
    
    'notifyFail' is similar to message, except it causes a failure notification
    to appear
    
    'notifySuccess' is similar to message, except a success message appears
    
    '''
    #Static add to every context
    addToContext = {    
                    'paceForm':paceForm(),
                    'rationsForm':rationForm(),
                    }
    #dynamic add to every context
    if 'currentGame' in request.session:
        addToContext['currentGame'] = request.session['currentGame']
    if 'message' in request.session and request.session['message']:
        addToContext['message'] = request.session['message']
        request.session['message'] = False
    if 'notifyFail' in request.session and request.session['notifyFail']:
        addToContext['notifyFail'] = request.session['notifyFail']
        request.session['notifyFail'] = False
    if 'notifySuccess' in request.session and request.session['notifySuccess']:
        addToContext['notifySuccess'] = request.session['notifySuccess']
        request.session['notifySuccess'] = False
    return addToContext

@login_required
def acceptTeamInfo(request):
    '''
    Function to handle startUpMenu data to initialize a party
    Inputs: request //TODO include what data needs to be in request and say it must be post data
    Outputs: Rendered HTTP response
    '''
    # create empty context dictionary for rendering the template
    context = {}
    context.update(csrf(request))
    
    # check if POST data was submitted (should only access this view via post)
    if request.method == 'POST':
        # load form data from client into a bound form instance of teamInfoForm
        print request.POST["startDate"]
        infoForm = teamInfoForm(request.POST)
        if infoForm.is_valid(): # if form data is valid, deal with it
            # create a new game and associate it with the user
            newGame = OTG(player=request.user)
            newGame.save()
            
            # create a new party for the user's game
            newParty = createParty(infoForm,newGame)

            
            # create all the members, main member first
            createCharacter(infoForm.cleaned_data['mainCharacter'],newParty,True)
            for i in range(1,5):
                currName = infoForm.cleaned_data['teamMember' + str(i)]
                createCharacter(currName,newParty,False)
            createWagon(newParty)
            request.session['currentGame']=newGame
            request.session['atStore']=True
            return HttpResponse(reverse('project.travel_game.views.locationHandler'))
        else: # if form data is not valid, return form with errors to user
            context['error']=True
            
        # render some short HTML of just the form
        context['teamInfoForm']=infoForm
        t = Template('{{ teamInfoForm.as_p }}{% if error %}<div id="error"></div>{% endif %}{% csrf_token %}<button id="continue" type="button" url="{% url travel_game.views.acceptTeamInfo %}" onclick="submitTeamInfo(this);">Go!</button>')
        return HttpResponse(t.render(Context(context)))

def login(request):
    '''
    function to log a user in
    inputs: request with POST data
    outputs: 
    //TODO describe what kind of data we need and the variables it should be called
    '''
    context = {}
    context.update(csrf(request))
    if request.method=='POST': # if data was posted, attempt to log user in
        # try to authenticate user using given username and password
        user = authenticate(username=request.POST['username'],password=request.POST['pwd'])
        if user is not None: # if user is logged in, log them in with django's auth system
            djangoLogin(request,user)
            # redirect to whatever url the user was trying to access
            #return HttpResponseRedirect(request.POST['next'])  # this line redirects to whatever page the unathenticated user
            # requested
            request.session['atStore'] = False
            if (OTG.objects.filter(player=user)):
                return HttpResponseRedirect(reverse('project.travel_game.views.currentGames'))
            else:
                return HttpResponseRedirect(reverse('project.travel_game.views.startUp'))
        print "failing"
        request.session['notifyFail'] = 'Username or Password was incorrect'
     # if the login failed or nothing was posted, redirect back to the login page
    context['userCreationForm']=userCreationForm()
    return render_to_response('html/login.html',context,context_instance=RequestContext(request))

@login_required
def currentGames(request):
    '''
    Function that finds all the current games for a ?player?
    Renders html/chooseGame.html
    '''
    context = {'allGames':OTG.objects.filter(player=request.user)}
    return render_to_response('html/chooseGame.html',context,context_instance=RequestContext(request))


def createParty(infoForm,newGame):
    '''
        Function to create a party from an infoForm
    '''
    newParty = Party(
     distanceFromStart=0,
     profession=infoForm.cleaned_data['profession'],
     game=newGame,
     rations=infoForm.cleaned_data['rations'],
     pace=infoForm.cleaned_data['pace'],
     money=infoForm.cleaned_data['profession'].startingMoney,
     date=infoForm.cleaned_data['startDate']
    )
    newParty.save()
    return newParty

def createWagon(newParty):
    '''
        Function to make a wagon
    '''
    newWagon = Wagon(
        name = 'Wagon',
        health = 10,
        party=newParty,
        isMain = False,
        kind = WAGON,
        carryWeight = WAGON_WEIGHT 
    )
    newWagon.save()

def createCharacter(currName,newParty,main):
    '''
        Function to make a character with some default health
    '''
    newMember = Member(
    name = currName,
    health = 10,
    party=newParty, 
    isMain = main,
    kind = CHARACTER,
    carryWeight = CHARACTER_WEIGHT                    
    )
    newMember.save()

@login_required
def loadGame(request,gameID=None):
    '''
        Function that given a game id sets the currentGame session variable to that game
    '''
    if gameID:
        request.session['currentGame']=OTG.objects.get(id=gameID)
        return locationHandler(request)
    else:
        return HttpResponseRedirect(reverse('project.travel_game.views.currentGames'))
    
    
def createStore(currGame):
    '''
        Function that creates an instance of a store template (abstract store)
        for a location if the current game doesn't have a store instance for
        that location yet.
        
        Inputs: currGame - the django object representing the current game
        Outputs: newStore - either a newly created store for the current
            location or a store that was already created for that location
    '''
    abstractStore = AbstractStore.objects.get(location=Landmark.objects.filter(distanceFromStart=currGame.party_set.all()[0].distanceFromStart))
    if not (abstractStore.store_set.filter(game=currGame)):
        newStore = Store(templateStore=abstractStore,game=currGame)
        newStore.save()
        for item in abstractStore.item_set.all():
            newItem = Item(itemType=item.itemType,quantity=item.quantity,holder=newStore)
            newItem.save()
            
    else:
        newStore = Store.objects.get(templateStore=abstractStore,game=currGame)
    
    return newStore

@login_required
def leaveLandmark(request):
    '''
        Function that calls move when you leave a landmark built to handle river weirdness
        Required session variables:
            currentGame
        If you are at a river then location handler is called if not then dayAction is called
    '''
    location = Landmark.objects.filter(distanceFromStart=request.session['currentGame'].party_set.all()[0].distanceFromStart)
    if location and isinstance(location[0],River):
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    move(request)
    return HttpResponseRedirect(reverse('project.travel_game.views.dayAction',args=[random.randint(0,1000)]))

@login_required    
def dayAction(request,num):
    '''
        Function to set up and render the normal day html page.  Also checks if
        the party is actually at a landmark and redirects them to that page
        if necessary.
        Inputs: request
                num - random, unused integer passed to avoid caching.
        Outputs: HttpResponse - either a redirect to a landmark page or a
            rendered day page.
    '''
    if atLandmark(request):
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    context = {}
    context.update(csrf(request))
    context['party'] = request.session['currentGame'].party_set.all()[0]
    food = context['party'].item_set.filter(itemType__name='Food')
    if food:
        food = food[0]
    context['food'] = food.quantity * food.itemType.weight
    context['paceForm']=paceForm()
    context['rationForm']=rationForm()
    return render_to_response('html/normalDay.html',context,context_instance=RequestContext(request))

@login_required
def changePace(request): 
    '''
        Function to change the pace of a currentGame's party when a paceFormInstance is posted 
        Required session variables:
            currentGame
    '''
    paceFormInstance=paceForm(request.GET)
    if paceFormInstance.is_valid(): 
        pace = paceFormInstance.cleaned_data['pace']
        currParty = request.session['currentGame'].party_set.all()[0]
        currParty.pace=pace
        currParty.save()
    return HttpResponse(pace)

@login_required
def changeRations(request):
    '''
        Function to change the rations of the current party
    '''
    rationFormInstance=rationForm(request.GET)
    if rationFormInstance.is_valid():
        rations = rationFormInstance.cleaned_data['rations']
        currParty = request.session['currentGame'].party_set.all()[0]
        currParty.rations=rations
        currParty.save()
    return HttpResponse(rations)

@login_required
def logout(request):
    '''
        Function Logs user out and redirects them to the login page
    '''
    djangoLogout(request)
    return HttpResponseRedirect(reverse('project.travel_game.views.login'))

def createOx(currentGame):
    '''
        Function that adds an oxen to the current party
    '''
    newMember = Member(
        name = 'Ox',
        health = 10,
        party=currentGame.party_set.all()[0],
        isMain = False,
        kind = OX,
        carryWeight = OX_WEIGHT                    
    )
    newMember.save()

def updatePartyItem(currentGame,itemID,amount,currStore,request):
    '''
        Function that removes items from a store inventory and puts them in a
        party inventory.  Also updates the money for a party (subtracts the 
        price of items from the party's money).
        Inputs: currentGame - the current player's game object
                itemID - the primary key of the item that was bought
                amount - the number of items bought
                currStore - the store object that the player is at
                request - user request data
        Outputs: sets session data and manipulates database objects, so none 
                really
    '''
    amount = int(amount)
    mult = Landmark.objects.get(distanceFromStart=currentGame.party_set.all()[0].distanceFromStart).costModifier
    thisParty = currentGame.party_set.all()[0]
    thisItem = thisParty.item_set.all().filter(itemType__pk=itemID)
    if thisParty.money - (AbstractItem.objects.get(pk=itemID).cost * amount * mult) >= 0:
        if AbstractItem.objects.get(pk=itemID).name=='Two Oxen':
            numberToCreate = amount * 2
            for i in range(0,numberToCreate):
                createOx(currentGame)
        else:
            if (thisItem):
                thisItem = thisItem[0]
                thisItem.quantity = thisItem.quantity + amount
            else:
                thisItem = Item(itemType=AbstractItem.objects.get(pk=itemID),quantity=amount,holder=thisParty)
            thisItem.save()
            
        storeItem = currStore.item_set.get(itemType__pk=itemID)
        storeItem.quantity = storeItem.quantity - amount
        storeItem.save()
        thisParty.money = thisParty.money - (AbstractItem.objects.get(pk=itemID).cost * amount * mult)
        thisParty.save()
    else:
        request.session['message'] = "You don't have enough money for that"
    
def getTotalWeight(currParty):
    '''
        Function calculates the weight of all of the items in a partys inventory
    '''
    totalWeight = 0
    for currItem in currParty.item_set.all():
        totalWeight = totalWeight + (currItem.itemType.weight * currItem.quantity)
    return totalWeight
    
@login_required
def renderStore(request):
    '''
        Function builds all the variables needed for the store html to render 
        then returns the rendered HTML
        Input: request
        Output: HttpResponse - rendered html store page
    '''
    context={}
    context.update(csrf(request))
    currStore = createStore(request.session['currentGame'])
    context['storeItems']=currStore.item_set.all()
    for item in context['storeItems']:
        item.itemType.cost = item.itemType.cost * Landmark.objects.get(distanceFromStart=request.session['currentGame'].party_set.all()[0].distanceFromStart).costModifier
    request.session['atStore']=True
    weightCap = 0
    for currMember in request.session['currentGame'].party_set.all()[0].member_set.all():
        weightCap = weightCap + currMember.carryWeight
    weightCap = weightCap - getTotalWeight(request.session['currentGame'].party_set.all()[0])
    context['partyWeightCap']=weightCap
    context['money']=request.session['currentGame'].party_set.all()[0].money
    context['numItems']=len(context['storeItems'])
    context['store']=currStore
    return render_to_response('html/store.html',context,context_instance=RequestContext(request))

@login_required
def buyItems(request):
    '''
        Function adds or subtracts items that are posted from a store for the current party
        then sets the party to not be at a store
        Required session variables:
            currentGame
            atStore
        Required POST variables:
            itemID's for every item in a store
    '''
    context={}
    context.update(csrf(request))
    currStore = createStore(request.session['currentGame'])
    if request.method=='POST':
        for itemID, value in request.POST.iteritems():
            if (not itemID=='csrfmiddlewaretoken'):
                updatePartyItem(request.session['currentGame'],itemID, value,currStore,request)
            request.session['atStore']=False
        return locationHandler(request)
    
@login_required
def sidebarView(request):
    '''
        Function renders sidebar.html
    '''
    context = {}
        
    return  render_to_response('html/sidebar.html',context,context_instance=RequestContext(request))  

@login_required
def locationHandler(request):
    '''
        Function is called to determine where the party is at and which function
        should determine the next action. The random variables are to keep 
        browsers such as chrome from caching the response.
        Inputs: request
        Outputs: HttpResponseRedirect (a redirect URL)
        
        Always returns a redirect response to the url of the function that 
        should be called
    '''
    if request.session['atStore']:
        return HttpResponseRedirect(reverse('project.travel_game.views.renderStore'))
    elif atLandmark(request):
        return HttpResponseRedirect(reverse('project.travel_game.views.landmarkAction',args=[random.randint(0,1000)]))
    else:
        return HttpResponseRedirect(reverse('project.travel_game.views.dayAction',args=[random.randint(0,1000)]))
    
def atLandmark(request):
    '''
        Function uses current game to see if there are anylandmarks at the
        parties current distance. Returns true if there is a landmark at the current distance
        and false otherwise. 
        //TODO make method take in current game instead of request
        Required session variables:
            currentGame:

    '''
    if Landmark.objects.filter(distanceFromStart=request.session['currentGame'].party_set.all()[0].distanceFromStart):
        return True
    else:
        return False
    
def deleteGame(request,gameID):
    '''
        Fuction deletes the game specified by game id
        Returns json with success message of either true or false
        //TODO give an example of json
        //to remove the need for for request by taking in user
    '''
    game = OTG.objects.filter(pk=gameID,player=request.user)
    if game:
        output={'id':game[0].pk}
        game.delete()
        output['success']=True
    else:
        output={'success':False}
    return HttpResponse(json.dumps(output))

@login_required    
def landmarkAction(request):
    '''
        Function uses a party's distanceFromStart to determine what type of
        landmark the party is currently at.  It then determines what html to
        render for that landmark.
        Inputs: request
        Outputs: response object of rendered html for the landmark

        Required context variables
            one of landmark store river
        Required Session variables 
            currentGame 
    '''
    currentLandmark = Landmark.objects.filter(distanceFromStart=request.session['currentGame'].party_set.all()[0].distanceFromStart)
    if currentLandmark is not None:
        currentLandmark = currentLandmark[0]
    else:
        return HttpResponseRedirect(reverse('project.travel_game.views.dayAction',args=[random.randint(0,1000)]))
    context={'landmark':currentLandmark}
    currStore = AbstractStore.objects.filter(location = currentLandmark)
    river = River.objects.filter(distanceFromStart = currentLandmark.distanceFromStart)
    if currStore:
        context['store'] = currStore[0]
    if river:
        context['river'] = river[0]
        return render_to_response('html/river.html',context,context_instance=RequestContext(request))
    elif currentLandmark.name=='END':
        return render_to_response('html/oregon.html',context,context_instance=RequestContext(request))
    else:
        return render_to_response('html/landmark.html',context,context_instance=RequestContext(request))

@login_required
def move(request):
    '''
        Function moves the party one day forward.  Increments the date, 
        increments distanceFromStart of the party based on the pace, decrements
        food based on rations level, and checks for randomEvents.
        
        Inputs: request
        Outputs: json dump object
        
        Output is a json dictionary object that contains keys used by the JS to
        determine what action to take on the normal day page.  The values update
        item amounts, and if the 'url' key exists then the user is redirected
        to that url
    '''
    currParty = request.session['currentGame'].party_set.all()[0]
    food = currParty.item_set.filter(itemType__name='Food')
    numCharacters = currParty.member_set.filter(kind=CHARACTER).count()
    foodConsumed = numCharacters*currParty.rations
    if food:
        food = food[0]
        food.quantity = food.quantity - foodConsumed
        if food.quantity<=0:
            food.quantity=0
        food.save()
    
    if (currParty.pace == 1):
        milesTraveled = 5
        currParty.distanceFromStart = currParty.distanceFromStart+milesTraveled
    elif (currParty.pace==2):
        milesTraveled = 10
        currParty.distanceFromStart = currParty.distanceFromStart+milesTraveled
    elif(currParty.pace==3):
        milesTraveled = 15
        currParty.distanceFromStart = currParty.distanceFromStart+milesTraveled
    currParty.date = currParty.date + timedelta(days=1)
    currParty.save()
    previousLandmarks= Landmark.objects.filter(distanceFromStart__lt=currParty.distanceFromStart)
    for currLandmark in previousLandmarks:
        if ((currParty.distanceFromStart - currLandmark.distanceFromStart) < milesTraveled):
            currParty.distanceFromStart = currLandmark.distanceFromStart
            currParty.save()
            output={'url':reverse('project.travel_game.views.locationHandler')}
            return HttpResponse(json.dumps(output))
            break
        else:
            if food:
                output={'distTraveled':currParty.distanceFromStart,'currFood':food.quantity}
            else:
                output={'distTraveled':currParty.distanceFromStart,'currFood':0}
    randomE = randomEvent(request)
    if randomE:
        output={'url':reverse('project.travel_game.views.locationHandler')}
        request.session['message']=randomE
    return HttpResponse(json.dumps(output))
    
def newUser(request):
    '''
       Funciotn renders the createUser page with the defult context variables  
    '''
    context={}
    context.update(csrf(request))
    return render_to_response('html/createUser.html',context,context_instance=RequestContext(request))

def createUser(request):
    '''
        Function uses information from the posted userCreationForm to make a user and 
        redirect them to the startup screen 

        Required POST variables:
            userCreationForm
        If the user didnt post data and this function is called it redirects to the login page.        
    '''
    context={}
    context.update(csrf(request))
    if request.method=='POST':
        userForm=userCreationForm(request.POST)
        if (userForm.is_valid()):
            username=userForm.cleaned_data['username']
            password=userForm.cleaned_data['password']
            email=userForm.cleaned_data['email']
            user = User.objects.create_user(username,email, password)
            user.save()
            user = authenticate(username = username,password = password)
            djangoLogin(request,user)
            return HttpResponseRedirect(reverse('project.travel_game.views.startUp'))
    return HttpResponseRedirect(reverse('project.travel_game.views.login'))


def ferry(request):
    '''
        Function moves the party across the river then deducts $35 from there money.
        
        Required session variables:
            currentGame
        If the party doesnt have $35 then ferry redirects them to locationHandler        
    '''
    party = request.session['currentGame'].party_set.all()[0]
    location = River.objects.filter(distanceFromStart=party.distanceFromStart)
    if not location or party.money < 35:
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    else:
        party.money = party.money - 35
        party.save()
        move(request)
        request.session['message'] = "Successfully crossed river and were\
        deducted $35"
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))

def ford(request):
    '''
        Function moves the part accross the river if it is deep enough and has the chance
        for items to be lost.

        Required session variables:
            currentGame

        If the river isnt deep enough then ford redirects user to locationHandler
    '''
    party = request.session['currentGame'].party_set.all()[0]
    location = River.objects.filter(distanceFromStart=party.distanceFromStart)
    if not location  or location[0].currentDepth>=3:
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    else:
        probToFail = .1
        if random.random() - probToFail < 0:
            probToDrown = .1
            if random.random() - probToDrown < 0:
                pass
            takePercentOfItems(party,10)
            move(request)
            request.session['message']="Your oxen collapsed in the mud, you \
            lost some stuff"
            return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
        request.session['message']="Successfully crossed river!"
        move(request)
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    
def takePercentOfItems(party,percent):
    '''
        Function removes a percentage of all items
    '''
    for item in party.item_set.all():
        item.quantity = item.quantity - math.floor((item.quantity*percent*.01))
        item.save()
        print 'ended with %d' % item.quantity
        
def takePercentOfItem(party,abstractItem,percent):
    '''
        Function removes a percentage of a single item
    '''
    item =party.item_set.filter(itemType=abstractItem) 
    if item:
        item = item[0]
        amountTaken = math.floor((item.quantity*percent*.01))
        item.quantity = item.quantity - amountTaken
        if item.quantity < 0:
            item.quantity = 0
            amountTaken = 0
        item.save()
        return "took %d units of %s" % (amountTaken, item.itemType.name)
    else:
        return "took nothing"
        
    

def caulk(request):
    '''
        Function moves a party accross a river with the greatest chance that they will lost items

        Required session variables:
            currentGame
    '''
    party = request.session['currentGame'].party_set.all()[0]
    location = River.objects.filter(distanceFromStart=party.distanceFromStart)
    if not location:
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    else:
        probToFail = .3
        if random.random() - probToFail < 0:
            probToDrown = .5
            if random.random() - probToDrown < 0:
                pass
            takePercentOfItems(party,20)
            move(request)
            request.session['message']="Your wagon flipped, tough spit"
            return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
        request.session['message']="Successfully crossed river!"
        move(request)
        return HttpResponseRedirect(reverse('project.travel_game.views.locationHandler'))
    
def randomEvent(request):
    '''
        Function to take items and make funny sayings 
        returns false if no random event should happen
    '''
    randomProb = .05
    randomAttackers = ['zombie babies','werewolves','rabid Tech professors','redheaded stepchildren','The Donner Party']
    randomItems = [(AbstractItem.objects.get(name='Food'),10),(AbstractItem.objects.get(name='Ammo'),30),(AbstractItem.objects.get(name='Clothing'),50)]
    if random.random() - randomProb < 0:
        attacker = randomAttackers[random.randint(0,len(randomAttackers)-1)]
        item = randomItems[random.randint(0,len(randomItems)-1)]
        itemString = takePercentOfItem(request.session['currentGame'].party_set.all()[0],item[0],item[1])
        return "You were attacked by %s and they %s" % (attacker, itemString)
    else:
        return False
    
def validateUsername(request,username):
    '''
        Function takes in a username and if it exists returns success=false in json
        returns success=true in json otherwise 
    '''
    if User.objects.filter(username=username):
        return HttpResponse(json.dumps({'success':False}))
    else:
        return HttpResponse(json.dumps({'success':True}))

def render(request):
    '''
        Function to use Django's template syntax rendering language to allow
        a javascript file to be rendered dynamically to contain json objects
        representing the options for pace and rations from their respective 
        classes
        Inputs: request
        Outputs: HttpResponse - rendered javascript file
    '''
    context={'paceOptions':Party.paceChoices,'rationsOptions':Party.rationChoices}
    return render_to_response('js/render.js',context,context_instance=RequestContext(request))
    
    
def calcTemp(month):
    if(month < 4 or month > 9):
         temp = 30
    else:
        temp = 110
    return temp
    
def crossRiverMoneyCheck(curMoney, costToCross):
    return curMoney >= costToCross
    
def foodChecker(curFood, amtToRemove):
    return curFood  >= amtToRemove


def unicode_escape(unistr):
    """
    Tidys up unicode entities into HTML friendly entities

    Takes a unicode string as an argument

    Returns a unicode string
    """
    import htmlentitydefs
    escaped = ""

    for char in unistr:
        if ord(char) in htmlentitydefs.codepoint2name:
            name = htmlentitydefs.codepoint2name.get(ord(char))
            entity = htmlentitydefs.name2codepoint.get(name)
            escaped +="&#" + str(entity)

        else:
            escaped += char

    return escaped   
    
def unicorn_kill(unistr):
    """
    Removes unicode entities

    Takes a unicode string as an argument

    Returns a unicode string
    """
    import htmlentitydefs
    escaped = ""

    for char in unistr:
        if ord(char) in htmlentitydefs.codepoint2name:
            name = htmlentitydefs.codepoint2name.get(ord(char))
            entity = htmlentitydefs.name2codepoint.get(name)
            escaped +=""

        else:
            escaped += char

    return escaped  
    
    
    
    
    
    
